import { sendSock } from '@/utils/socketSend'
import { websocketonmessage } from '@/utils/socketOnMessage'
import tools from './tools'
import store from '@/store'

// 创建空的webSocket对象
let webSocket = null
// websocket地址
const wsUrl = process.env.VUE_APP_SOCKET_URL

// 初始化websocket连接
const initWebsocket = () => {
  // ws地址
  webSocket = new WebSocket(wsUrl)
  webSocket.binaryType = 'arraybuffer'
  // 数据接收
  webSocket.onmessage = (e) => {
    websocketonmessage(e)
    heartCheck.start()
  }
  // 关闭连接
  webSocket.onclose = (e) => {
    if (!tools.storage.getHfSession()) {
      return
    }
    reconnect(wsUrl)
  }
  // 连接成功
  webSocket.onopen = () => {
    // 心跳检测重置
    heartCheck.start()
  }
  // 发生错误
  webSocket.onerror = () => {
    reconnect(wsUrl)
  }
  return webSocket
}

// 心跳检测
const heartCheck = {
  // 每隔十秒发送一次心跳
  timeout: 10000,
  // 两次心跳均未响应就重连
  num: 2,
  timeoutObj: null,
  start: function () {
    let innerNum = this.num
    this.timeoutObj && clearTimeout(this.timeoutObj)
    this.timeoutObj = setTimeout(() => {
      // 发送心跳 后端收到后返回心跳信息
      sendSock({
        type: '5.1.3',
        body: ''
      })
      innerNum--
      // 计算答复的超时次数
      if (innerNum === 0) {
        webSocket.close()
      }
    }, this.timeout)
  }
}

// 重连操作
let lockReconnect = false
let tt = null
const reconnect = (url) => {
  if (lockReconnect) {
    return
  }
  lockReconnect = true
  // 没连上会一直重连
  tt && clearTimeout(tt)
  tt = setTimeout(() => {
    store.dispatch('socket/initWS')
    lockReconnect = false
  }, 5000)
}

export {
  initWebsocket,
  heartCheck
}
